// 命令行交互 lib/interface/cli.ts
import { ChatHistory } from '../chat/history';
import { ApiService } from '../../services/api.service';
import { print, printError } from '../chat/utils';
import { ChatLogger } from '../logger';
import { cli } from './cli-manager'
import { config } from '../../config'

export class CLIInterface {
  // private rl = readline.createInterface({
  //   input: process.stdin,
  //   output: process.stdout,
  //   prompt: '\n👤 你：'
  // });
  private cli = cli;

  constructor(
    private readonly history: ChatHistory,
    private readonly apiService: ApiService,
    private readonly logger: ChatLogger
  ) {}

  start(): void {
    console.log(`配置模型为：${config.MODEL}`)
    console.log(`🚀 DeepSeek 聊天机器人已启动,（输入 exit 退出）`);
    this.cli.showPrompt() // 显示提示符
    // 监听用户输入
    this.cli.interface.on('line', this.handleInput.bind(this));
    // 监听输入流关闭
    this.cli.interface.on('close', () => this.shutdown());
  }
  // 处理用户输入的字符串
  private async handleInput(input:string) {
    if (input.toLowerCase() === 'exit') return this.shutdown();

    await this.history.add({ role: 'user', content: input.trim() });
    try {
      print('\n🤖 思考中...', 'thinking');
      // 调用api
      await this.apiService.getAIResponse();
      // 记录对话日志
      await this.logger.append(this.history.getMessages())
    } catch (error : any) {
      printError(`请求失败：${error.message}`);
    }
    this.cli.showPrompt(); // getAIResponse()写入时会关闭提示符，所以要打开
  } 
  // 关闭cli端口：提示+移除事件+退出程序
  private shutdown(): void {
    print('\n👋 再见！', 'system');
    this.cli.interface.removeAllListeners()
    this.cli.close()
    process.exit(0);
  }
}
